package com.zzyl.nursing.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.dto.IotMsgNotifyData;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;

/**
 * 设备数据Service业务层处理
 * 
 * @author zhq
 * @date 2025-08-23
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void batchInsetDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        //判断设备是否存在
        String iotId= iotMsgNotifyData.getHeader().getDeviceId();
        Device device=deviceMapper.selectOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId,iotId));
        if(Objects.isNull(device)){
            log.error("设备不存在");
            return;
        }
        //获取设备上报的数据,一个设备可以有多个service
        iotMsgNotifyData.getBody().getServices().forEach(
                s->{
                    //所有数据都已经装入到map中
                    Map<String, Object> properties = s.getProperties();
                    if(ObjectUtil.isEmpty(properties)){
                        return;
                    }
                    LocalDateTime eventTime = LocalDateTimeUtil.parse(s.getEventTime(), Constants.LOCAL_DATE_FORMATTER);
                    LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                            .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                            .toLocalDateTime();

                    ArrayList<DeviceData> deviceDataList = new ArrayList<>();
                    properties.forEach((key,value)->{
                        DeviceData deviceData = DeviceData.builder()
                                .iotId(iotId)
                                .deviceName(device.getDeviceName())
                                .productKey(device.getProductKey())
                                .productName(device.getProductName())
                                .functionId(key)
                                .accessLocation(device.getRemark())
                                .locationType(device.getLocationType())
                                .physicalLocationType(device.getPhysicalLocationType())
                                .deviceDescription(device.getDeviceDescription())
                                .alarmTime(alarmTime)
                                .dataValue(value + "")
                                .build();
                        deviceDataList.add(deviceData);
                    });

                    saveBatch(deviceDataList);
                    redisTemplate.opsForHash().put(Constants.IOT_DEVICE_LAST_DATA,iotId, deviceDataList);
                }

        );
    }

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param deviceDataPageReqDto 设备数据
     * @return 设备数据
     */
    @Override
    public TableDataInfo selectDeviceDataList(DeviceDataPageReqDto deviceDataPageReqDto)
    {
        Page<DeviceData> page = Page.of(deviceDataPageReqDto.getPageNum(), deviceDataPageReqDto.getPageSize());
        lambdaQuery().eq(!StringUtils.isBlank(deviceDataPageReqDto.getDeviceName()),DeviceData::getDeviceName,deviceDataPageReqDto.getDeviceName())
                .eq(!StringUtils.isBlank(deviceDataPageReqDto.getFunctionId()),DeviceData::getFunctionId,deviceDataPageReqDto.getFunctionId())
                .between(!ObjectUtil.isEmpty(deviceDataPageReqDto.getStartTime())&&!ObjectUtil.isEmpty(deviceDataPageReqDto.getEndTime()),DeviceData::getCreateTime,deviceDataPageReqDto.getStartTime(),deviceDataPageReqDto.getEndTime())
                .page(page);
        TableDataInfo tableData = new TableDataInfo();
        tableData.setCode(HttpStatus.SUCCESS);
        tableData.setMsg("查询成功");
        tableData.setRows(page.getRecords());
        tableData.setTotal(page.getTotal());
        return tableData;
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return deviceDataMapper.deleteById(id);
    }
}
